package uk.co.droidinactu.sony.prst1.home;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import uk.co.droidinactu.AboutIntents;
import uk.co.droidinactu.sony.prst1.home.data.Book;
import uk.co.droidinactu.sony.prst1.home.data.SonyDataModel;
import uk.co.droidinactu.sony.prst1.home.view.ApplicationsActivity;
import uk.co.droidinactu.sony.prst1.home.view.BookDetailsActivity;
import uk.co.droidinactu.sony.prst1.home.view.BookSortBy;
import uk.co.droidinactu.sony.prst1.home.view.BooksActivity;
import uk.co.droidinactu.sony.prst1.home.view.CollectionsActivity;
import uk.co.droidinactu.sony.prst1.home.view.HorizontialListView;
import uk.co.droidinactu.sony.prst1.home.view.Page2Activity;
import uk.co.droidinactu.sony.prst1.home.view.PeriodicalsActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public final class SonyPrsT1HomeActivity extends Activity implements OnItemSelectedListener, OnClickListener {

    private static final int ACTIVITY_EDIT_PREFERENCES = 8192;

    private static final String LAUNCHPAD_TRANSLATOR_CREDITS_HEADER = "Launchpad Contributions: ";

    private static final String LAUNCHPAD_TRANSLATOR_CREDITS_TAG = "translator-credits";
    private static final String LAUNCHPAD1_TRANSLATOR_CREDITS_SEPARATOR = ";";
    private static final String LAUNCHPAD2_TRANSLATOR_CREDITS_REGEX = "("
            + SonyPrsT1HomeActivity.LAUNCHPAD1_TRANSLATOR_CREDITS_SEPARATOR + " )|("
            + SonyPrsT1HomeActivity.LAUNCHPAD1_TRANSLATOR_CREDITS_SEPARATOR + ")";

    public static final String LOG_TAG = "SonyPrsT1HomeActivity";

    public static final int MENU_ABOUT = 5;
    public static final int MENU_CLEAR_DEFAULTS = 4;
    public static final int MENU_PREFERENCES = 1;
    public static final int MENU_SETTINGS = 2;
    public static final int NUMBER_BOOKS_ON_SHELF = 4;

    /**
     * copy one file to a new file.
     * 
     * @param in
     *            the file to make the copy of.
     * @param out
     *            the destination for the copy of the file.
     * @throws Exception
     */
    public static void copyFile(final File in, final File out) throws Exception {
        final FileInputStream fis = new FileInputStream(in);
        final FileOutputStream fos = new FileOutputStream(out);
        try {
            final byte[] buf = new byte[1024];
            int i = 0;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        } catch (final Exception e) {
            throw e;
        } finally {
            fis.close();
            fos.close();
        }
    }

    /**
     * Show an about dialog for this application.
     */
    public static void showAboutWithExtras(final Activity cntxt) {
        final Intent aboutDlgIntnt = new Intent(AboutIntents.ACTION_SHOW_ABOUT_DIALOG);

        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_PACKAGE_NAME, cntxt.getPackageName());

        // alternative 2: Supply the image name and package.
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_ICON_RESOURCE,
                cntxt.getResources().getResourceName(R.drawable.ic_launcher));

        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_APPLICATION_LABEL, cntxt.getString(R.string.app_name));

        // Get the app version
        final String version = ((SonyPrsT1HomeApplication) cntxt.getApplication()).getApplicationVersion();
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_VERSION_NAME, version);

        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_COMMENTS, cntxt.getString(R.string.app_explanation));
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_COPYRIGHT, cntxt.getString(R.string.about_copyright));
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_WEBSITE_LABEL, cntxt.getString(R.string.about_website_label));
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_WEBSITE_URL, cntxt.getString(R.string.about_website_url));
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_AUTHORS, cntxt.getResources().getStringArray(R.array.about_authors));
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_DOCUMENTERS,
                cntxt.getResources().getStringArray(R.array.about_documenters));

        // Create string array of translators from translated string from
        // Launchpad or (for English) from the array.
        final String translatorsString = cntxt.getString(R.string.about_translators);
        if (translatorsString.equals(SonyPrsT1HomeActivity.LAUNCHPAD_TRANSLATOR_CREDITS_TAG)) {
            aboutDlgIntnt.putExtra(AboutIntents.EXTRA_TRANSLATORS,
                    cntxt.getResources().getStringArray(R.array.about_translators));
        } else {
            final String[] translatorsArray = translatorsString.replaceFirst(
                    SonyPrsT1HomeActivity.LAUNCHPAD_TRANSLATOR_CREDITS_HEADER, "").split(
                    SonyPrsT1HomeActivity.LAUNCHPAD2_TRANSLATOR_CREDITS_REGEX);
            aboutDlgIntnt.putExtra(AboutIntents.EXTRA_TRANSLATORS, translatorsArray);
        }

        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_ARTISTS, cntxt.getResources().getStringArray(R.array.about_artists));

        // Supply resource name of raw resource that contains the license:
        aboutDlgIntnt.putExtra(AboutIntents.EXTRA_LICENSE_RESOURCE,
                cntxt.getResources().getResourceName(R.raw.license_short));

        // Start about activity. Needs to be "forResult" with requestCode>=0
        // because the About dialog may call elements from your Manifest by your
        // package name.
        if (((SonyPrsT1HomeApplication) cntxt.getApplication())
                .isIntentAvailable(AboutIntents.ACTION_SHOW_ABOUT_DIALOG)) {
            cntxt.startActivityForResult(aboutDlgIntnt, 0);
        } else {
            final AlertDialog.Builder builder = new AlertDialog.Builder(cntxt);
            builder.setMessage("OI About not installed!").setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(final DialogInterface dialog, final int id) {
                            dialog.cancel();
                        }
                    });
            final AlertDialog alert = builder.create();
            alert.show();
        }
    }

    private Button btnApps;
    private Button btnBooks;
    private Button btnCollections;
    private ImageButton btnNextPage;
    private Button btnPeriodicals;

    private int collection1Start = 0;
    private int collection2Start = 0;
    private Book contextMenuSelectedBook = null;
    private int currentlyReadingStart = 0;
    private Cursor cursrCollcnts1;
    private Cursor cursrCollcnts2;
    private Cursor cursrCurrentRead;
    private ImageView imgBtnCollection1Next;
    private ImageView imgBtnCollection1Prev;
    private ImageView imgBtnCollection2Next;
    private ImageView imgBtnCollection2Prev;
    private ImageView imgBtnCurrentReadNext;
    private ImageView imgBtnCurrentReadPrev;
    private TextView lblClock;
    private TextView lblCollection1;
    private TextView lblCollection2;
    private TextView lblCurrentRead;

    private SimpleCursorAdapter listAdapterCollectns1;
    private SimpleCursorAdapter listAdapterCollectns2;
    private SimpleCursorAdapter listAdapterCurrentRead;
    private HorizontialListView listviewCollectns1;

    private HorizontialListView listviewCollectns2;

    private HorizontialListView listviewCurrentRead;

    private SonyDataModel sonyDataModel;

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        switch (requestCode) {
        case ACTIVITY_EDIT_PREFERENCES:
            this.updateCurrentlyReading();
            this.updateCollectionlist1();
            this.updateCollectionlist2();
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onClick(final View v) {
        if (v.getTag().equals("apps")) {
            this.startActivity(new Intent(this.getApplication(), ApplicationsActivity.class));
        } else if (v.getTag().equals("collections")) {
            this.startActivity(new Intent(this.getApplication(), CollectionsActivity.class));
        } else if (v.getTag().equals("books")) {
            this.startActivity(new Intent(this.getApplication(), BooksActivity.class));
        } else if (v.getTag().equals("periodicals")) {
            this.startActivity(new Intent(this.getApplication(), PeriodicalsActivity.class));
        } else if (v.getTag().equals("nextpage")) {
            this.startActivity(new Intent(this.getApplication(), Page2Activity.class));
        } else if (v.getTag().equals("next_currnt_read")) {
            this.currentlyReadingStart = this.currentlyReadingStart + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF;
            this.updateCurrentlyReading();
        } else if (v.getTag().equals("prev_currnt_read")) {
            this.currentlyReadingStart = this.currentlyReadingStart - SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF;
            if (this.currentlyReadingStart < 0) {
                this.currentlyReadingStart = 0;
            }
            this.updateCurrentlyReading();
        } else if (v.getTag().equals("next_collection1")) {
            this.collection1Start = this.collection1Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF;
            this.updateCollectionlist1();
        } else if (v.getTag().equals("prev_collection1")) {
            this.collection1Start = this.collection1Start - SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF;
            if (this.collection1Start < 0) {
                this.collection1Start = 0;
            }
            this.updateCollectionlist1();
        } else if (v.getTag().equals("next_collection2")) {
            this.collection2Start = this.collection2Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF;
            this.updateCollectionlist2();
        } else if (v.getTag().equals("prev_collection2")) {
            this.collection2Start = this.collection2Start - SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF;
            if (this.collection2Start < 0) {
                this.collection2Start = 0;
            }
            this.updateCollectionlist2();
        }
        this.updateCurrentTime();
    }

    @Override
    public boolean onContextItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            Log.d(SonyPrsT1HomeApplication.LOG_TAG + SonyPrsT1HomeActivity.LOG_TAG, "Show details of book: "
                    + this.contextMenuSelectedBook.toString());
            this.startActivity(new Intent(this, BookDetailsActivity.class));
            return true;
        case 1:
            Log.d(SonyPrsT1HomeApplication.LOG_TAG + SonyPrsT1HomeActivity.LOG_TAG, "Delete book: "
                    + this.contextMenuSelectedBook.toString());
            // this.myApp.getCalibreController().deleteBook(this.myApp.contextMenuSelectedBook);
            return true;
        default:
            return super.onContextItemSelected(item);
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.page1);

        try {
            final File f1 = new File(
                    "/data/data/uk.co.droidinactu.sony.prst1.home/shared_prefs/uk.co.droidinactu.sony.prst1.home_preferences.xml");
            final File f2 = new File("/sdcard/sonyprst1home_shared_prefs.xml");
            if (!f1.exists() && f2.exists()) {
                copyFile(f2, f1);
            }
        } catch (final Exception e) {
            Log.e(SonyPrsT1HomeApplication.LOG_TAG, LOG_TAG + "Exception ", e);
        }

        final File f = new File("/data/data/uk.co.droidinactu.sony.prst1.home/databases/SonyPrsT1HomeDb");
        if (f.exists()) {
            f.delete();
            f.deleteOnExit();
        }

        this.btnNextPage = (ImageButton) this.findViewById(R.id.page1_btn_nextpage);
        this.btnNextPage.setVisibility(View.INVISIBLE);
        final TextView txtPageNbr = (TextView) this.findViewById(R.id.page1_text_page_number);
        txtPageNbr.setVisibility(View.INVISIBLE);

        this.btnPeriodicals = (Button) this.findViewById(R.id.page1_btn_periodicals);
        this.btnCollections = (Button) this.findViewById(R.id.page1_btn_collections);
        this.btnApps = (Button) this.findViewById(R.id.page1_btn_apps);
        this.btnBooks = (Button) this.findViewById(R.id.page1_btn_books);
        this.lblClock = (TextView) this.findViewById(R.id.page1_text_clock);

        this.lblCurrentRead = (TextView) this.findViewById(R.id.page1_text_currently_reading_lbl);
        this.lblCollection1 = (TextView) this.findViewById(R.id.page1_text_collection1_lbl);
        this.lblCollection2 = (TextView) this.findViewById(R.id.page1_text_collection2_lbl);

        this.listviewCurrentRead = (HorizontialListView) this.findViewById(R.id.page1_current_reading);
        this.listviewCollectns1 = (HorizontialListView) this.findViewById(R.id.page1_collections_list1);
        this.listviewCollectns2 = (HorizontialListView) this.findViewById(R.id.page1_collections_list2);

        this.imgBtnCurrentReadNext = (ImageView) this.findViewById(R.id.page1_btn_next_currnt_read);
        this.imgBtnCurrentReadPrev = (ImageView) this.findViewById(R.id.page1_btn_prev_currnt_read);

        this.imgBtnCollection1Next = (ImageView) this.findViewById(R.id.page1_btn_next_collection1);
        this.imgBtnCollection1Prev = (ImageView) this.findViewById(R.id.page1_btn_prev_collection1);

        this.imgBtnCollection2Next = (ImageView) this.findViewById(R.id.page1_btn_next_collection2);
        this.imgBtnCollection2Prev = (ImageView) this.findViewById(R.id.page1_btn_prev_collection2);

        this.btnNextPage.setOnClickListener(this);
        this.btnApps.setOnClickListener(this);
        this.btnBooks.setOnClickListener(this);
        this.btnCollections.setOnClickListener(this);
        this.btnPeriodicals.setOnClickListener(this);

        this.imgBtnCurrentReadNext.setOnClickListener(this);
        this.imgBtnCurrentReadPrev.setOnClickListener(this);

        this.imgBtnCollection1Next.setOnClickListener(this);
        this.imgBtnCollection1Prev.setOnClickListener(this);

        this.imgBtnCollection2Next.setOnClickListener(this);
        this.imgBtnCollection2Prev.setOnClickListener(this);
    }

    @Override
    public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        final MenuInflater inflater = this.getMenuInflater();
        inflater.inflate(R.menu.book_lst_cntxt_mnu, menu);

        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

        if (v.getId() == R.id.page1_current_reading) {
            // get data from cursrCurrentRead
            this.cursrCurrentRead.moveToPosition(info.position);
            this.contextMenuSelectedBook = new Book(this.cursrCurrentRead);
        } else if (v.getId() == R.id.page1_collections_list1) {
            // get data from cursrCollcnts1
            this.cursrCollcnts1.moveToPosition(info.position);
            this.contextMenuSelectedBook = new Book(this.cursrCurrentRead);
        } else if (v.getId() == R.id.page1_collections_list2) {
            // get data from cursrCollcnts2
            this.cursrCollcnts2.moveToPosition(info.position);
            this.contextMenuSelectedBook = new Book(this.cursrCurrentRead);
        }
        if (this.contextMenuSelectedBook != null) {
            menu.setHeaderTitle(this.contextMenuSelectedBook.title);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, SonyPrsT1HomeActivity.MENU_SETTINGS, 0, R.string.menu_settings).setIcon(
                android.R.drawable.ic_menu_preferences);
        menu.add(0, SonyPrsT1HomeActivity.MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon(
                android.R.drawable.ic_menu_preferences);
        menu.add(0, SonyPrsT1HomeActivity.MENU_CLEAR_DEFAULTS, 0, R.string.menu_clear_default_settings).setIcon(
                android.R.drawable.ic_menu_close_clear_cancel);
        menu.add(0, SonyPrsT1HomeActivity.MENU_ABOUT, 0, R.string.menu_about).setIcon(R.drawable.ic_menu_about);

        return true;
    }

    @Override
    public void onItemSelected(final AdapterView<?> av, final View v, final int pos, final long id) {
        this.sonyDataModel.launchBook(this, id);
    }

    @Override
    public void onNothingSelected(final AdapterView<?> arg0) {
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        boolean retvalue = false;
        switch (item.getItemId()) {
        case MENU_PREFERENCES:
            this.startActivityForResult(new Intent(this.getApplication(), EditPreferences.class),
                    SonyPrsT1HomeActivity.ACTIVITY_EDIT_PREFERENCES);
            retvalue = true;
            break;

        case MENU_SETTINGS:
            this.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
            retvalue = true;
            break;

        case MENU_CLEAR_DEFAULTS:
            final PackageManager pm = this.getPackageManager();
            pm.clearPackagePreferredActivities("uk.co.droidinactu.sony.prst1.home");
            pm.clearPackagePreferredActivities("com.android.launcher");
            retvalue = true;
            break;

        case MENU_ABOUT:
            this.showAboutWithExtras();
            retvalue = true;
            break;

        default:
            return super.onOptionsItemSelected(item);
        }
        return retvalue;
    }

    @Override
    protected void onPause() {
        super.onPause();

        try {
            final File f1 = new File(
                    "/data/data/uk.co.droidinactu.sony.prst1.home/shared_prefs/uk.co.droidinactu.sony.prst1.home_preferences.xml");
            final File f2 = new File("/sdcard/sonyprst1home_shared_prefs.xml");
            copyFile(f1, f2);
        } catch (final Exception e) {
            Log.e(SonyPrsT1HomeApplication.LOG_TAG, LOG_TAG + "Exception ", e);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (this.sonyDataModel == null) {
            this.sonyDataModel = new SonyDataModel(this.getApplication());
        }

        long nbrBooks = 0;
        long nbrCollections = 0;
        long nbrPeriodicals = 0;
        Cursor tmpCursor = this.sonyDataModel.getBooks(this.getApplication(), BookSortBy.TITLE);
        if (tmpCursor != null) {
            nbrBooks = tmpCursor.getCount();
            tmpCursor.close();
        }
        tmpCursor = this.sonyDataModel.getCollections(0, 9999, null);
        if (tmpCursor != null) {
            nbrCollections = tmpCursor.getCount();
            tmpCursor.close();
        }
        tmpCursor = this.sonyDataModel.getPeriodicals(this.getApplication());
        if (tmpCursor != null) {
            nbrPeriodicals = tmpCursor.getCount();
            tmpCursor.close();
        }

        final PackageManager manager = this.getPackageManager();
        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);

        this.btnApps.setText(String.format(this.getResources().getString(R.string.page1_Apps), apps.size()));
        this.btnBooks.setText(String.format(this.getResources().getString(R.string.page1_Books), nbrBooks));
        this.btnCollections.setText(String.format(this.getResources().getString(R.string.page1_Collections),
                nbrCollections));
        this.btnPeriodicals.setText(String.format(this.getResources().getString(R.string.page1_Periodicals),
                nbrPeriodicals));

        this.updateCurrentlyReading();
        this.updateCollectionlist1();
        this.updateCollectionlist2();

        this.updateCurrentTime();
    }

    private void setupList(final HorizontialListView listview, final SimpleCursorAdapter listAdapter, final Cursor cursr) {
        if (cursr == null || cursr != null && cursr.getCount() == 0) {
            Toast.makeText(this.getApplication(), "No books available", Toast.LENGTH_LONG);
        } else {
            listview.setOnItemSelectedListener(this);
            listAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
                @Override
                public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
                    boolean retval = false;
                    final int idColIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID);
                    final int thumbColIndex = cursor.getColumnIndexOrThrow(Book.COLUMN_NAME_THUMBNAIL);

                    if (columnIndex == idColIndex) {
                        try {
                            final ImageView coverImg = (ImageView) view;
                            final String thumbnailFilename = cursor.getString(thumbColIndex);
                            final Bitmap bitmap = SonyDataModel.getBookCoverImg(SonyPrsT1HomeActivity.this,
                                    thumbnailFilename);
                            coverImg.setImageDrawable(new BitmapDrawable(bitmap));
                            retval = true;
                        } catch (final Exception e) {
                            Log.e(SonyPrsT1HomeApplication.LOG_TAG, SonyPrsT1HomeActivity.LOG_TAG + "Exception ", e);
                        }
                        retval = true;
                    }
                    return retval;
                }
            });
            listview.setAdapter(listAdapter);
            this.registerForContextMenu(listview);
            this.startManagingCursor(cursr);
        }
    }

    /**
     * Show an about dialog for this application.
     */
    public void showAboutWithExtras() {
        SonyPrsT1HomeActivity.showAboutWithExtras(this);
    }

    private void updateCollectionlist1() {
        try {
            final String clctname = EditPreferences.getCollectionName1(this.getApplication());

            if (clctname.equals(this.getResources().getString(R.string.pref_collection_recently_added))) {
                this.cursrCollcnts1 = this.sonyDataModel.getRecentlyAdded(this);
                final int nbrItems = this.cursrCollcnts1.getCount();
                if (this.collection1Start >= nbrItems) {
                    this.collection1Start = nbrItems - 1;
                }
                final String tmpStr;
                if (this.collection1Start + 1 < nbrItems) {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_1),
                            this.collection1Start + 1, this.collection1Start
                                    + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF > nbrItems ? nbrItems
                                    : this.collection1Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, nbrItems);
                } else {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_2),
                            this.collection1Start + 1, nbrItems);
                }
                this.lblCollection1.setText(clctname + " " + tmpStr);
                this.cursrCollcnts1.close();
                this.cursrCollcnts1 = this.sonyDataModel.getRecentlyAdded(this, this.collection1Start,
                        SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF);

            } else if (clctname.equals(this.getResources().getString(R.string.pref_collection_periodicals))) {
                this.cursrCollcnts1 = this.sonyDataModel.getPeriodicals(this);
                final int nbrItems = this.cursrCollcnts1.getCount();
                if (this.collection1Start >= nbrItems) {
                    this.collection1Start = nbrItems - 1;
                }
                final String tmpStr;
                if (this.collection1Start + 1 < nbrItems) {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_1),
                            this.collection1Start + 1, this.collection1Start
                                    + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF > nbrItems ? nbrItems
                                    : this.collection1Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, nbrItems);
                } else {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_2),
                            this.collection1Start + 1, nbrItems);
                }
                this.lblCollection1.setText(clctname + " " + tmpStr);
                this.cursrCollcnts1.close();
                this.cursrCollcnts1 = this.sonyDataModel.getPeriodicals(this, this.collection1Start,
                        SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF);

            } else {
                this.cursrCollcnts1 = this.sonyDataModel.getBooksInCollection(clctname, BookSortBy.TITLE);
                final int nbrItems = this.cursrCollcnts1.getCount();
                if (this.collection1Start >= nbrItems) {
                    this.collection1Start = nbrItems - 1;
                }
                final String tmpStr;
                if (this.collection1Start + 1 < nbrItems) {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_1),
                            this.collection1Start + 1, this.collection1Start
                                    + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF > nbrItems ? nbrItems
                                    : this.collection1Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, nbrItems);
                } else {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_2),
                            this.collection1Start + 1, nbrItems);
                }
                this.lblCollection1.setText(clctname + " " + tmpStr);
                this.cursrCollcnts1.close();
                this.cursrCollcnts1 = this.sonyDataModel.getBooksInCollection(this.getApplication(), clctname,
                        this.collection1Start, SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, BookSortBy.TITLE);
            }

            if (EditPreferences.useFilenames(this)) {
                this.listAdapterCollectns1 = new SimpleCursorAdapter(this, R.layout.book_grid_item_filename,
                        this.cursrCollcnts1, BooksActivity.bookColumnsFilename, BooksActivity.bookColsMapToFilename);
            } else {
                this.listAdapterCollectns1 = new SimpleCursorAdapter(this, R.layout.book_grid_item,
                        this.cursrCollcnts1, BooksActivity.bookColumns, BooksActivity.bookColsMapTo);
            }
            this.setupList(this.listviewCollectns1, this.listAdapterCollectns1, this.cursrCollcnts1);
        } catch (final Exception e) {
            Log.e(SonyPrsT1HomeApplication.LOG_TAG, SonyPrsT1HomeActivity.LOG_TAG + "Exception ", e);
        }
    }

    private void updateCollectionlist2() {
        try {
            final String clctname = EditPreferences.getCollectionName2(this.getApplication());

            if (clctname.equals(this.getResources().getString(R.string.pref_collection_recently_added))) {
                this.cursrCollcnts2 = this.sonyDataModel.getRecentlyAdded(this);
                final int nbrItems = this.cursrCollcnts2.getCount();
                if (this.collection2Start >= nbrItems) {
                    this.collection2Start = nbrItems - 1;
                }
                final String tmpStr;
                if (this.collection2Start + 1 < nbrItems) {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_1),
                            this.collection2Start + 1, this.collection2Start
                                    + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF > nbrItems ? nbrItems
                                    : this.collection2Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, nbrItems);
                } else {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_2),
                            this.collection1Start + 1, nbrItems);
                }
                this.lblCollection2.setText(clctname + " " + tmpStr);
                this.cursrCollcnts2.close();
                this.cursrCollcnts2 = this.sonyDataModel.getRecentlyAdded(this, this.collection2Start,
                        SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF);

            } else if (clctname.equals(this.getResources().getString(R.string.pref_collection_periodicals))) {
                this.cursrCollcnts2 = this.sonyDataModel.getPeriodicals(this);
                final int nbrItems = this.cursrCollcnts2.getCount();
                if (this.collection2Start >= nbrItems) {
                    this.collection2Start = nbrItems - 1;
                }
                final String tmpStr;
                if (this.collection2Start + 1 < nbrItems) {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_1),
                            this.collection2Start + 1, this.collection2Start
                                    + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF > nbrItems ? nbrItems
                                    : this.collection2Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, nbrItems);
                } else {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_2),
                            this.collection2Start + 1, nbrItems);
                }
                this.lblCollection2.setText(clctname + " " + tmpStr);
                this.cursrCollcnts2.close();
                this.cursrCollcnts2 = this.sonyDataModel.getPeriodicals(this, this.collection2Start,
                        SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF);

            } else {
                this.cursrCollcnts2 = this.sonyDataModel.getBooksInCollection(clctname, BookSortBy.TITLE);
                final int nbrItems = this.cursrCollcnts2.getCount();
                if (this.collection2Start >= nbrItems) {
                    this.collection2Start = nbrItems - 1;
                }
                final String tmpStr;
                if (this.collection2Start + 1 < nbrItems) {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_1),
                            this.collection2Start + 1, this.collection2Start
                                    + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF > nbrItems ? nbrItems
                                    : this.collection2Start + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, nbrItems);
                } else {
                    tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_2),
                            this.collection2Start + 1, nbrItems);
                }
                this.lblCollection2.setText(clctname + " " + tmpStr);
                this.cursrCollcnts2.close();
                this.cursrCollcnts2 = this.sonyDataModel.getBooksInCollection(this.getApplication(), clctname,
                        this.collection2Start, SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, BookSortBy.TITLE);
            }

            if (EditPreferences.useFilenames(this)) {
                this.listAdapterCollectns2 = new SimpleCursorAdapter(this, R.layout.book_grid_item_filename,
                        this.cursrCollcnts2, BooksActivity.bookColumnsFilename, BooksActivity.bookColsMapToFilename);
            } else {
                this.listAdapterCollectns2 = new SimpleCursorAdapter(this, R.layout.book_grid_item,
                        this.cursrCollcnts2, BooksActivity.bookColumns, BooksActivity.bookColsMapTo);
            }
            this.setupList(this.listviewCollectns2, this.listAdapterCollectns2, this.cursrCollcnts2);
        } catch (final Exception e) {
            Log.e(SonyPrsT1HomeApplication.LOG_TAG, SonyPrsT1HomeActivity.LOG_TAG + "Exception ", e);
        }
    }

    private void updateCurrentlyReading() {
        try {
            this.cursrCurrentRead = this.sonyDataModel.getCurrentlyReading(this.getApplication());
            final int nbrItems = this.cursrCurrentRead.getCount();
            if (this.currentlyReadingStart >= nbrItems) {
                this.currentlyReadingStart = nbrItems - 1;
            }
            final String tmpStr;
            if (this.currentlyReadingStart + 1 < nbrItems) {
                tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_1),
                        this.currentlyReadingStart + 1, this.currentlyReadingStart
                                + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF > nbrItems ? nbrItems
                                : this.currentlyReadingStart + SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF, nbrItems);
            } else {
                tmpStr = String.format(this.getResources().getString(R.string.page1_nbr_item_format_2),
                        this.currentlyReadingStart + 1, nbrItems);
            }
            this.lblCurrentRead.setText(this.getResources().getString(R.string.page1_currently_reading_lbl) + " "
                    + tmpStr);
            this.cursrCurrentRead.close();
            this.cursrCurrentRead = this.sonyDataModel.getCurrentlyReading(this.getApplication(),
                    this.currentlyReadingStart, SonyPrsT1HomeActivity.NUMBER_BOOKS_ON_SHELF);
            if (EditPreferences.useFilenames(this)) {
                this.listAdapterCurrentRead = new SimpleCursorAdapter(this, R.layout.book_grid_item_filename,
                        this.cursrCurrentRead, BooksActivity.bookColumnsFilename, BooksActivity.bookColsMapToFilename);
            } else {
                this.listAdapterCurrentRead = new SimpleCursorAdapter(this, R.layout.book_grid_item,
                        this.cursrCurrentRead, BooksActivity.bookColumns, BooksActivity.bookColsMapTo);
            }
            this.setupList(this.listviewCurrentRead, this.listAdapterCurrentRead, this.cursrCurrentRead);
        } catch (final Exception e) {
            Log.e(SonyPrsT1HomeApplication.LOG_TAG, SonyPrsT1HomeActivity.LOG_TAG + "Exception ", e);
        }
    }

    private void updateCurrentTime() {
        this.lblClock.setText(DateFormat.format("kk:mm:ss", new Date()));
    }
}
